package com.acwing.lc.part1;

/**
 * @author rkc
 * @date 2022/9/19 10:24
 */
public class LC71简化路径 {

    public String simplifyPath(String path) {
        StringBuilder ans = new StringBuilder(), name = new StringBuilder();
        if (path.charAt(path.length() - 1) != '/') path += '/';
        for (int i = 0; i < path.length(); i++) {
            if (path.charAt(i) != '/') name.append(path.charAt(i));
            else {
                if ("..".equals(name.toString())) {
                    while (ans.length() != 0 && ans.charAt(ans.length() - 1) != '/') {
                        ans.deleteCharAt(ans.length() - 1);
                    }
                    if (ans.length() != 0) ans.deleteCharAt(ans.length() - 1);
                } else if (!".".equals(name.toString()) && !"".equals(name.toString())) {
                    ans.append('/').append(name);
                }
                name.delete(0, name.length());
            }
        }
        if (ans.length() == 0) ans.append('/');
        return ans.toString();
    }
}
